package com.donghaiair.framework.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringBeanUtil implements ApplicationContextAware {
	private static ApplicationContext context;

	/**
	 * 一般使用
	 * 
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static Object getBean(String name) throws Exception {
		if (context == null) {
			throw new Exception("获得beanFactory异常，请检查spring配置文件！");
		}
		return context.getBean(name);
	}
	
	/**
	 * Autowired时，可以使用
	 * 
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public static Object getBean(Class<?> clazz) throws Exception {
		if (context == null) {
			throw new Exception("获得beanFactory异常，请检查spring配置文件！");
		}
		AutowireCapableBeanFactory a = context.getAutowireCapableBeanFactory();
		Object bean = a.getBean(clazz);
		return bean;
	}

	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		context = arg0;
	}
}